<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style type="text/css">
        .router-link-exact-active {
            color: white;
            background-color: green;
        }
    </style>
</head>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router@3.5.1/dist/vue-router.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

<body>
    <div id="app">
        <div><input type="text" v-model="currentTime" @input="updateCurrentTime"></div>
        <div style="display: flex;align-items: center;justify-content:space-between">
            <span title="把时间改成YYYY-MM-DD HH:MM:SS格式得5分">当前时间：{{currentTime}}</span>
            <span title="根据时间读取对应的课程、教师、班级的10分">当前课程：{{currentCourse}}</span>
            <span title="根据时间读取对应的课程、教师、班级的10分">当前教师：{{currentTeacher}}</span>
            <span title="根据时间读取对应的课程、教师、班级的10分">当前班级：{{currentClass}}</span>
        </div>
        <div>
            <input type="date" v-model="selectedDate" @change="getDayOfWeek(selectedDate)">
            <p>你选择的日期：{{selectedDate}}</p>
        </div>
        <keep-alive include="Home">
            <router-view></router-view>
        </keep-alive>
    </div>

    <template id="daohangTemp">
        <div style="display: flex;align-items: center;justify-content:space-between">
            <router-link to="/">同学列表(20分)</router-link>

            <router-link to="/about">座位(20分)</router-link>

            <router-link to="/person">抽奖(45分)</router-link>
        </div>
    </template>

    <!----定义一些组件-->
    <template id="HomeTemp">
        <div>
            <daohang></daohang>
            <div>
                <ul>
                    <li v-for="list in studenst_name">{{list.name}}</li>
                </ul>
            </div>
        </div>
    </template>


    <template id="AboutTemp">
        <div>
            <daohang></daohang>
            <br>
            <div>
                <table class="table" border="1">
                    <tr>
                        <td v-for="student in students">
                            {{ student.name }}
                        </td>
                    </tr>
                </table>
            </div>
        </div>
    </template>


    <template id="PersonTemp">
        <div>
            <daohang></daohang>
            <br>
            <div>
                两个按钮，一个按钮点<button @click="startChanging">开始</button> ， 然后在本试图中显示三个同学，不断的轮换背景色
                如

                <br>
                <!-- <ul>
                    <li>同学1</li>
                    <li style="background-color: green;">同学2</li>
                    <li>同学3</li>
                </ul> -->
                <ul>
                    <li v-for="(student, index) in students" :key="index"
                        :style="{'background-color': index === activeIndex ? 'green' : ''}">
                        {{ student.name }}</li>
                </ul>
                <br>
                点击<button @click="stopChanging">停止</button>，晚3秒在某个同学上停住背景色
            </div>
        </div>
    </template>

</body>
<script>

    var daoHang = Vue.component('daohang', { template: '#daohangTemp' });
    var Home = Vue.component('Home', {
        template: '#HomeTemp',
        data: function () {
            return {
                clickCounter: 0,
                studenst_name: []
            }
        },
        methods: {
        },
        mounted: function () {
            const that = this;
            that.studenst_name = [{ "name": "同学名" }];
            axios.get('/web_final/json/class.json')
                .then(function (res) {
                    if (res.status == 200) {
                        console.log(res.data[0].studentList[0].name)
                        that.studenst_name = res.data[0].studentList;
                    }
                });
        }
    });



    var About = Vue.component('About', {
        template: '#AboutTemp',
        data: function () {
            return {
                students: ['同学1', '同学2', '同学3'],
            }
        },
        mounted: function () {
            const that = this;
            axios.get('/web_final/json/class.json')
                .then(function (res) {
                    if (res.status == 200) {
                        that.students = res.data[0].studentList;
                    }
                });
        }
    });



    var Person = Vue.component('Person', {
        template: '#PersonTemp',
        data: function () {
            return {
                // currentTime: new Date(),
                // currentCourse: "无",
                // currentClass: "无",
                // currentTeacher: "无",
                // schedule: {},
                // selectedDate: '',
                students: ['同学1', '同学2', '同学3'],
                activeIndex: -1,
                intervalId: null,
                // data: ''
            }
        },
        methods: {
            startChanging() {
                if (this.intervalId) return; // 如果已经在循环中，则不重新开始
                this.intervalId = setInterval(() => {
                    this.activeIndex = (this.activeIndex + 1) % this.students.length;
                }, 90); // 每90毫秒改变一次
            },
            stopChanging() {
                if (this.intervalId) {
                    setTimeout(() => {
                        clearInterval(this.intervalId);
                        this.intervalId = null;
                    }, 3000); // 延迟3000毫秒后清除循环
                }
            },
            getCurrentCourse() {
                // 在这里直接使用 currentCourse 数据属性
                return this.currentCourse;
            }
        },

        mounted: async function () {
            const that = this;
            var a =this.getCurrentCourse();
            console.log(a);
            await axios.get('/web_final/json/kebiao.json')
                .then(function (res) {
                    if (res.status == 200) {
                        const data = res.data;
                        console.log(data);
                    }
                });
            await axios.get('/web_final/json/class.json')
                .then(function (res) {
                    if (res.status == 200) {
                        // let filteredUsers = res.data.studenst.filter(studenst => studenst.name == that.studenst_name);
                        // console.log(res.data.studenst.filter(studenst => studenst.name === that.studenst_name))
                        // console.log(filteredUsers);
                        that.students = res.data[0].studentList;
                        // if (filteredUsers.length > 0) {
                        //     that.icon_list = filteredUsers[0].icon;
                        // }
                    }
                });
        },
        // mounted: function () {
        //     const that = this;
        //     // Promise.all([
        //     //     axios.get('/web_final/json/class.json'),
        //     //     axios.get('/web_final/json/kebiao.json')
        //     // ]).then(function (responses) {
        //     //     // 使用新的数据更新schedule
        //     //     const classData = responses[0].data;
        //     //     const scheduleData = responses[1].data;
        //     //     console.log(classData);
        //     //     // 获取当前时间段
        //     //     const currentCourseTime = this.getCurrentCourseTime();
        //     //     console.log(currentCourseTime);
        //     //     // 假设课表数据是按时间段组织的
        //     //     // 根据当前时间段找到对应的课程
        //     //     const currentSchedule = scheduleData.find(schedule => schedule.timeSlot === currentCourseTime);
        //     //     if (currentSchedule) {
        //     //         // 假设currentSchedule结构中有className字段
        //     //         const currentClassName = currentSchedule.className;
        //     //         // 过滤classData来找到匹配的className
        //     //         let filteredClass = classData.find(item => item.className === currentClassName);
        //     //         if (filteredClass) {
        //     //             // 假设filteredClass结构中有name字段
        //     //             this.students = filteredClass.studentList;
        //     //         }
        //     //     }
        //     //     // 调用processSchedule方法来处理新的数据
        //     //     this.processSchedule(scheduleData);
        //     // });
        //     axios.get('/web_final/json/class.json')
        //         .then(function (res) {
        //             if (res.status == 200) {
        //                 // let filteredUsers = res.data.filter(className => className == that.currentClass)
        //                 // console.log(filteredUsers);
        //                 // console.log(res.data[0].studentList[0].name)
        //                 that.students = res.data[0].studentList;
        //             }
        //         });
        //     axios.get('/web_final/json/kebiao.json')
        //         .then(function (res) {
        //             if (res.status == 200) {
        //                 that.schedule = res.data;
        //                 // that.getCurrentClass();
        //             }
        //         });
        // }
    });

    // 创建 router 实例
    var router = new VueRouter({
        routes: [
            { path: '/', component: Home },
            { path: '/about', component: About },
            { path: "/person", component: Person }
        ]
    });

    // 创建和挂载根实例
    new Vue({
        data: {
            currentTime: new Date(),
            currentCourse: "无",
            currentClass: "无",
            currentTeacher: "无",
            schedule: {},
            selectedDate: ''
        },
        el: '#app',
        router,
        methods: {
            formatTime() {
                const currentDate = new Date();
                // 格式化日期：YYYY年MM月DD日
                const year = currentDate.getFullYear();
                const month = String(currentDate.getMonth() + 1).padStart(2, '0');
                const day = String(currentDate.getDate()).padStart(2, '0');
                // 格式化时间：HH时MM分SS秒
                const hours = String(currentDate.getHours()).padStart(2, '0');
                const minutes = String(currentDate.getMinutes()).padStart(2, '0');
                const seconds = String(currentDate.getSeconds()).padStart(2, '0');
                this.currentTime = `${year}-${month}-${day}\t${hours}:${minutes}:${seconds}`;
            },
            getDayOfWeek(dateString) {
                console.log(dateString);
                const date = new Date(dateString);
                const daysOfWeek = ["sunday", "monday", "tuesday", "wendesday", "thursday", "friday", "saturday"];
                return daysOfWeek[date.getDay()];
            },
            getCurrentCourseTime(inputTime) {
                const now = inputTime ? new Date(inputTime) : new Date();
                // const now = new Date();
                const hour = now.getHours();
                const minute = now.getMinutes();
                // 定义时间段
                const timeSlots = {
                    '1-2': { start: { hour: 8, minute: 40 }, end: { hour: 10, minute: 0 } },
                    '3-4': { start: { hour: 10, minute: 20 }, end: { hour: 11, minute: 40 } },
                    '5-6': { start: { hour: 13, minute: 30 }, end: { hour: 14, minute: 50 } },
                    '7-8': { start: { hour: 15, minute: 10 }, end: { hour: 16, minute: 30 } },
                };
                // 遍历时间段，检查当前时间是否在某个时间段内
                for (const timeSlot in timeSlots) {
                    const start = timeSlots[timeSlot].start;
                    const end = timeSlots[timeSlot].end;

                    if (hour > start.hour || (hour === start.hour && minute >= start.minute)) {
                        if (hour < end.hour || (hour === end.hour && minute < end.minute)) {
                            return timeSlot; // 当前时间落在该时间段内
                        }
                    }
                }
                return null; // 当前时间没有落在任何时间段内
            },
            processSchedule(data, currentTime, selectedDate_Time) {
                // 假设data是kebiao.json的内容
                // 提取键名（星期）
                const days = Object.keys(data);
                // 假设我们关心的是今天的课程
                const today = new Date().getDay(); // 获取今天是星期几（0-6，0是星期日）
                const dayNames = ["sunday", "monday", "tuesday", "wendesday", "thursday", "friday", "saturday"];
                const currentDay = selectedDate_Time ? this.getDayOfWeek(selectedDate_Time) : dayNames[today];
                // console.log(today)
                console.log(dayNames[today])
                // 如果今天是星期一，获取星期一的课表
                if (currentDay in data) {
                    this.schedule = data[currentDay];
                    // 假设我们关心的是当前时间的课程
                    const currentCourseTime = this.getCurrentCourseTime(currentTime);
                    // 根据时间段找到课程、教师、班级信息
                    this.schedule.forEach(period => {
                        if (period[currentCourseTime]) {
                            this.currentCourse = period[currentCourseTime];
                            this.currentClass = period["className"];
                            this.currentTeacher = period["teacherName"];
                        }
                    });
                }
            },
            updateCurrentTime(event) {
                // 获取输入框中的值
                const inputValue = event.target.value;
                // 更新currentTime的值
                this.currentTime = inputValue;
                const regex = /^(\d{4})-(\d{2})-(\d{2})\t([01]?[0-9]|2[0-3]):[0-5][0-9]:(\d{2})$/;
                const isValid = regex.test(inputValue);
                // 如果输入的值有效，则更新currentTime
                if (isValid) {
                    this.currentTime = inputValue;
                } else {
                    // 如果不合法，可以清空输入框的值或者给出提示
                    alert("请输入正确的时间");
                }
                console.log(inputValue)
                // 调用axios.get来重新获取数据
                axios.get('/web_final/json/kebiao.json')
                    .then(response => {
                        if (response.status === 200) {
                            // 使用新的数据更新schedule
                            this.schedule = response.data;
                            // 调用processSchedule方法来处理新的数据
                            this.processSchedule(response.data, this.currentTime, this.selectedDate);
                        }
                    });
            },
        },
        mounted: function () {
            // const currentCourseTime = this.getCurrentCourseTime();
            this.formatTime();
        },
    })
</script>

</html>